<?php

namespace x_mier\utils;

/**
 * @title DB处理方法
 */
class Db
{
    /**
     * 批量更新数据
     * @param string $table_name
     * @param array $data
     * @param string $field
     * @return bool|false|int
     */
    public static function db_batch_update($table_name, $data, $field)
    {
        if (!$table_name || !$data || !$field) {
            return false;
        } else {
            $sql = 'UPDATE ' . $table_name;
        }
        $con = [];
        $con_sql = [];
        $fields = [];
        foreach ($data as $key => $value) {
            $x = 0;
            foreach ($value as $k => $v) {
                !isset($con_sql[$x]) && $con_sql[$x] = '';
                !isset($con[$x]) && $con[$x] = '';
                if ($k != $field && !$con[$x] && $x == 0) {
                    $con[$x] = " set {$k} = (CASE {$field} ";
                } elseif ($k != $field && !$con[$x] && $x > 0) {
                    $con[$x] = " {$k} = (CASE {$field} ";
                }
                if ($k != $field) {
                    $temp = $value[$field];
                    $con_sql[$x] .= " WHEN {$temp} THEN {$v} ";
                    $x++;
                }
            }
            $temp = $value[$field];
            if (!in_array($temp, $fields)) {
                $fields[] = $temp;
            }
        }
        $num = count($con) - 1;
        foreach ($con as $key => $value) {
            foreach ($con_sql as $k => $v) {
                if ($k == $key && $key < $num) {
                    $sql .= $value . $v . ' end),';
                } elseif ($k == $key && $key == $num) {
                    $sql .= $value . $v . ' end)';
                }
            }
        }
        $str = implode(',', $fields);
        $sql .= " where {$field} in({$str})";
        $res = \think\facade\Db::execute($sql);
        return $res;
    }
}
